#!/usr/bin/env python
# encoding: utf-8
# author: 04

from django_mysql.utils import index_name

from main import _script_head  # noqa
from main import config
from main.apps.purification import models as pr_models
from main.common.redis.redis_cli import RedisClientOrderContent
from main.common.redis.redis_keys import PURIFY_SUBORDERGEN_INSTANT_KEY, CHANGE_ORDER_CUSTOMER_PURIFY_CONF_KEY
from main.models.data_map import AUDIT_ORDER_INITIAL
from main.service.purify_suborder import *  # noqa


class PurifySuborderGenInstant(PurifySuborderGen):

    conflict_key = 'PurifySuborderGenInstant1'

    def task(self):
        if config.ENV not in ['test_ci', 'dev']:
            close_old_connections()  # https://www.jianshu.com/p/d2ba42feee15  避免长时间运行之后出现 MySQL server has gone away

        self.logger.info('MainQueue: <Stand Alone>Purification Suborder Generator starting...')
        self.recover_from_db()
        self.init_new_order()
        self.recover_from_queue()

        if self.loop_times % self.ENV_PRINT_PER_LOOP == 0:
            info = self.main_queue.len_from_all_data()
            self.logger.info(f'MainQueue: loop {self.loop_times} Now info: {json.dumps(info, indent=2)}')

    def init_new_order(self, ):
        def get_to_split_qs(purify_config, urgency_val, content_type_val):
            r_key = PURIFY_SUBORDERGEN_INSTANT_KEY.format(
                purify_config=purify_config.id, urgency_val=urgency_val, content_type_val=content_type_val)
            _ids = []

            for ii in range(self.FILL_PER_STEP):
                _id = RedisClientOrderContent.rpop(r_key)
                if _id:
                    _id = int(_id)
                    _ids.append(_id)
                else:
                    break
            if _ids:
                print('_ids', _ids[:10])
            print('r_key', r_key)
            print('len(_ids)', len(_ids))

            cache_set = RedisClient.smembers(CHANGE_ORDER_CUSTOMER_PURIFY_CONF_KEY)
            cache_set = [int(ii) for ii in cache_set]
            for _id in cache_set:
                RedisClientOrderContent.lpush(r_key, _id)

            index_result_sync = index_name(pr_models.AuditOrder, 'result_sync')
            order_qs = pr_models.AuditOrder.objects.force_index(index_result_sync).filter(
                result_sync=AUDIT_ORDER_INITIAL,
                id__in=_ids,
            ).select_related(
                'customer_purifyconfig'
            ).order_by('id')[:self.FILL_PER_STEP]
            return order_qs
        return self._init_new_order(get_to_split_qs)


if __name__ == "__main__":
    print('conflict_key', PurifySuborderGenInstant().conflict_key)
    PurifySuborderGenInstant().run()
